package com.xy.generate.util;

import com.xy.generate.config.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

public class DynamicGenerator {
    private final static Configuration CONFIGURATION;

    static {
        //初始化freemarker配置
        CONFIGURATION = new Configuration(Configuration.VERSION_2_3_32);
    }

    @SneakyThrows
    public static void doGenerate(String input, String output, Object model) {
        //指定模版文件所在的路径
        //CONFIGURATION.clearTemplateCache();
        File parentFile = new File(input).getParentFile();
        CONFIGURATION.setDirectoryForTemplateLoading(parentFile);
        CONFIGURATION.setDefaultEncoding("UTF-8");
        //创建模版对象
        String templateName = new File(input).getName();
        Template template = CONFIGURATION.getTemplate(templateName);
        //创建数据模型
        MainTemplateConfig mainTemplateConfig = MainTemplateConfig.builder().loop(false).author("tzf").outputText("sum= ").build();
        //生成
        Writer fileWriter = new FileWriter(output);
        template.process(model == null ? mainTemplateConfig : model, fileWriter);
        fileWriter.flush();
        //关闭流
        fileWriter.close();
    }
}
